//
//  HXSiteSelectViewController.m
//  KD
//
//  Created by ifly on 16/4/19.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXSiteSelectViewController.h"
#import "HXSitePictureViewController.h"
#import "HXGISViewController.h"
#import "HXLocaleJobTableViewController.h"
//#import "HXPictureGatherViewController.h"

@interface HXSiteSelectViewController ()<HXGISViewControllerDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *selectSiteBtt;//工地
@property (weak, nonatomic) IBOutlet UITextView *selectSiteTextView;
@property (weak, nonatomic) IBOutlet UITextView *contentTextField;//任务描述
@property (weak, nonatomic) IBOutlet UITextView *locationLabel;//地点
@property (weak, nonatomic) IBOutlet UITextView *referPersonTextField;//检查人员
@property (weak, nonatomic) IBOutlet UITextView *checkTime;//时间
@property (weak, nonatomic) IBOutlet UIScrollView *backScrollView;//背景

@property(nonatomic,copy)NSString *pointX;
@property(nonatomic,copy)NSString *pointY;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *keyGUID;
@property(nonatomic,strong)HXLocaleJobTableViewController * hxvc;
//@property(nonatomic,strong)HXSitePictureViewController *Vc;
@property(nonatomic,copy)NSString * nowNetTime;

@end

@implementation HXSiteSelectViewController

//-(void)viewDidAppear:(BOOL)animated{
//    
//    [super viewDidAppear:animated];
//    self.navigationController.navigationBar.translucent = YES;
//    
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.locationLabel.layer.borderWidth = 1;
    _selectSiteBtt.titleLabel.numberOfLines = 0;
    UIButton *backButton=[[UIButton alloc]init];
    // 设置返回图片
    [backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    backButton.contentMode = UIViewContentModeLeft;
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    // [button sizeToFit];//让按钮大小跟随内容
    // 让按钮的内容往左边偏移10
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame=CGRectMake(0, 0,37,90);
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:backButton];
    
    _backScrollView.delegate = self;
    _backScrollView.bounces = NO;
    _backScrollView.showsVerticalScrollIndicator = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _locationLabel.layer.cornerRadius = 8.0f;
    _locationLabel.layer.masksToBounds = YES;
    _locationLabel.layer.borderColor = [[UIColor blackColor] CGColor];
    _locationLabel.layer.borderWidth = 0.5f;
    _contentTextField.layer.cornerRadius = 8.0f;
    _contentTextField.layer.masksToBounds = YES;
    _contentTextField.layer.borderColor = [[UIColor blackColor] CGColor];
    _contentTextField.layer.borderWidth = 0.5f;
    _referPersonTextField.layer.cornerRadius = 8.0f;
    _referPersonTextField.layer.masksToBounds = YES;
    _referPersonTextField.layer.borderColor = [[UIColor blackColor] CGColor];
    _referPersonTextField.layer.borderWidth = 0.5f;
    _checkTime.layer.cornerRadius = 8.0f;
    _checkTime.layer.masksToBounds = YES;
    _checkTime.layer.borderColor = [[UIColor blackColor] CGColor];
    _checkTime.layer.borderWidth = 0.5f;
}

-(void)back {
    [self.navigationController popViewControllerAnimated:YES];
    _hxvc = [[HXLocaleJobTableViewController alloc] init];
    _hxvc.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
}

- (void)refreshData {
    [SVProgressHUD showWithStatus:@"正在加载"];
    [NetworkAPI localeJobWithNum:@"0"
                         success:^(HXLocaleJobModel *result) {
                             [_hxvc.dataArray addObjectsFromArray:result.resultlist];
                             if ([result.code isEqualToString:@"200"]) {
                                 [_hxvc.tableView reloadData];
                                 [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                 [_hxvc.tableView.mj_header endRefreshing];
                             }
                             if ([result.code isEqualToString:@"400"]) {
                                 [_hxvc.tableView.mj_header endRefreshing];
                                 [SVProgressHUD showSuccessWithStatus:@"暂无数据"];
                             }
                             if ([result.code isEqualToString:@"500"]) {
                                 [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                 [_hxvc.tableView.mj_header endRefreshing];
                             }
                         } failure:^(NSError *err) {
                             [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                             [_hxvc.tableView.mj_header endRefreshing];
                         }];
}

- (IBAction)selectSiteBttClick:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Apply" bundle:nil];
    HXGISViewController *meVc = [sb instantiateViewControllerWithIdentifier:@"HXGISViewController"];
    meVc.delegate = self;
    meVc.type = GISTypeNameType;
    meVc.title = @"选择工地";
    [self.navigationController pushViewController:meVc animated:YES];
}

- (IBAction)nextBtnClick:(id)sender {

    if (self.locationLabel.text.length == 0 || self.locationLabel.text == nil) {
        
        self.locationLabel.text = @"暂无工地地址";
    }
    
    //判断输入信息是否为空
    if (self.contentTextField.text.length == 0 || self.selectSiteBtt.titleLabel.text == 0 || self.referPersonTextField.text.length == 0) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"输入信息不完整" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * buttonAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:buttonAction];
        [self presentViewController:alertController animated:YES completion:^{
        }];
        return;
    }
    //获取网络时间
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            _nowNetTime = [NSString stringWithFormat:@"%@",result.ServerDate];
            NSLog(@"网络时间数据==================%@",result.ServerDate);
            [self createNextNetWork];
        }
    } failure:^(NSError *err) {
        _nowNetTime = [GlobalUtil getNowPhoneTime];
        [self createNextNetWork];
        //[SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
}

-(void)createNextNetWork {
    //将列表时间转化为Date数据
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *netTimeDate = [dateFormatter dateFromString:_nowNetTime];
    //能修改的时间
    //将现在时间转换成工作日
    NSCalendar * myCalendar = [NSCalendar currentCalendar];
    myCalendar.timeZone = [NSTimeZone systemTimeZone];
    NSDate * updateDate;
    NSString *updateTime = [[NSString alloc] init];
    NSTimeInterval oneDay = 24*60*60*1;
    //周日 周一 周二 周三 周四
    updateDate = [netTimeDate initWithTimeIntervalSinceNow:+oneDay];
    updateTime = [dateFormatter stringFromDate:updateDate];
    if ([GlobalUtil isNilValue:self.keyGUID]) {
        [SVProgressHUD showErrorWithStatus:@"项目信息为空,请重新选择工地"];
        return;
    }
    [NetworkAPI createPunishWithUserId:[UserDefaultHandler getUserDetault:kID]
                              SiteName:self.selectSiteBtt.titleLabel.text
                                 KGUID:self.keyGUID
                               SiteAdd:self.locationLabel.text
                             GroupName:self.referPersonTextField.text
                       SiteWorkContent:self.contentTextField.text
                                pointX:self.pointX
                                pointY:self.pointY
                            CreateDate:self.nowNetTime
                            UpdateDate:updateTime
                               success:^(HXCreatePunishModel *result) {
                                   [SVProgressHUD dismiss];
                                   
                                   NSDictionary * siteDetaileDic =
                                          @{@"ID":result.taskid,
                                            @"Task_SiteName":self.selectSiteBtt.titleLabel.text,
                                            @"Task_SiteAdd":self.locationLabel.text,
                                            @"Task_WorkID":@"",
                                            @"Task_WorkAPMGuid":@"",
                                            @"Task_SiteWorkContent":self.contentTextField.text,
                                            @"Task_DateTime":self.nowNetTime,
                                            @"Task_UpDateTime":updateTime,
                                            @"Task_X":self.pointX,
                                            @"Task_Y":self.pointY,
                                            @"Task_KeyGuid":self.keyGUID,
                                            @"SubmitDate":@"",
                                            @"Task_Type":@"1",
                                            @"Task_GroupName":self.referPersonTextField.text,};
                                   
                                   
                                   HXSitePictureViewController * sitePicVc = [HXSitePictureViewController CreateSitePictureVCWithTaskID:result.taskid withIsAdd:YES withIsListOrRiZhiPush:NO withIsExistTaskId:NO withLocalDataDic:siteDetaileDic];
                                   
                                   [self.navigationController pushViewController:sitePicVc animated:YES];
                               }
                               failure:^(NSError *err) {
                                   [SVProgressHUD showErrorWithStatus:@"网络错误"];
                               }];
    
}
#pragma mark - HXGISViewControllerDelegate
//根据code拿到工地地址坐标
- (void)siteName:(NSString *)name address:(NSString *)address{
    /**三个元素 是否在建     名字    id*/
    NSArray *array = [address componentsSeparatedByString:@"$"];
    if (array.count >= 2) {
        self.locationLabel.text = array[1];
    }
    if (array.count >= 3) {
        self.keyGUID = array[2];
    }
    if (array.count >= 4) {
        self.pointX = array[3];//x
    }
    if (array.count >= 5) {
        self.pointY = array[4];//y
    }
    [self.selectSiteBtt setTitle:name forState:UIControlStateNormal];
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            _nowNetTime = [NSString stringWithFormat:@"%@",result.ServerDate];
            NSLog(@"网络时间数据==================%@",result.ServerDate);
            _checkTime.text = _nowNetTime;
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,使用本地时间"];
        
        _checkTime.text = [GlobalUtil getNowPhoneTime];
        
    }];
}

@end
